/*
 *  Copyright 2007 Blandware (http://www.blandware.com)
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.blandware.atleap.webapp.action.core.contentField;

import com.blandware.atleap.common.Constants;
import com.blandware.atleap.model.core.*;
import com.blandware.atleap.service.core.LookupManager;
import com.blandware.atleap.webapp.util.core.WebappUtil;
import org.apache.struts.tiles.ComponentContext;
import org.apache.struts.tiles.ControllerSupport;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;


/**
 * <p>Content field list controller. This class is used to check can user create content fields or not.
 * </p>
 * <p><a href="ContentFieldListController.java.html"><i>View Source</i></a></p>
 *
 * @author Sergey Zubtsovskiy <a href="mailto:sergey.zubtsovskiy@blandware.com">&lt;sergey.zubtsovskiy@blandware.com&gt;</a>
 * @version $Revision: 1.7 $ $Date: 2007/12/13 13:53:03 $
 */
public final class ContentFieldListController extends ControllerSupport {
	//~ Methods ================================================================
	/**
	 * Retrieves content fields from persistence layer and put 'em to the request
	 *
	 * @param tilesContext   Current tile context
	 * @param request        Current request
	 * @param response       Current response
	 * @param servletContext Current Servlet Context
	 */
	public void execute(ComponentContext tilesContext, HttpServletRequest request, HttpServletResponse response, ServletContext servletContext)
	        throws Exception {

		Long ownerId = (Long) request.getAttribute("ownerId");
		if ( ownerId != null ) {
			ApplicationContext applicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
			LookupManager lookupManager = (LookupManager) applicationContext.getBean(Constants.LOOKUP_MANAGER_BEAN);
			Localizable owner = lookupManager.retrieveLocalizable(ownerId);

            if (owner instanceof ActionPage) {
                Set identifiers = WebappUtil.getOverridableFieldIdentifiers(owner, request);
                Map overridenAPFields = new HashMap();
                List fields = owner.getContentFields();
                for (int i = 0; i < fields.size(); i++) {
                    ContentField field = (ContentField) fields.get(i);
                    String identifier = field.getIdentifier();
                    int k = identifier.indexOf('[');
                    String identifierWithoutIndex;
                    if (k != -1) {
                        identifierWithoutIndex = identifier.substring(0, k);
                    } else {
                        identifierWithoutIndex = identifier;
                    }
                    overridenAPFields.put(identifier, new Boolean(identifiers.contains(identifierWithoutIndex)));
                }
                request.setAttribute("overridenAPFields", overridenAPFields);
            }

            if (owner instanceof Layout) {
                Set identifiers = WebappUtil.getOverridableFieldIdentifiers(owner, request);
                Map overridenLayoutFields = new HashMap();
                List fields = owner.getContentFields();
                for (int i = 0; i < fields.size(); i++) {
                    ContentField field = (ContentField) fields.get(i);
                    String identifier = field.getIdentifier();
                    int k = identifier.indexOf('[');
                    String identifierWithoutIndex;
                    if (k != -1) {
                        identifierWithoutIndex = identifier.substring(0, k);
                    } else {
                        identifierWithoutIndex = identifier;
                    }
                    overridenLayoutFields.put(identifier, new Boolean(identifiers.contains(identifierWithoutIndex)));
                }
                request.setAttribute("overridenLayoutFields", overridenLayoutFields);
            }

			if ( owner != null ) {
				Set identifiers = null;
				if ( owner instanceof ContentPage || (owner instanceof ActionPage && !request.isUserInRole("core-contentField-create") && !request.isUserInRole("core-contentField-update")) ) {
					identifiers = WebappUtil.getOverridableFieldIdentifiers(owner, request);
					if ( identifiers != null && !identifiers.isEmpty() ) {
						request.setAttribute("canCreateOrUpdate", "true");
					}
				} else if ( owner instanceof Layout && !request.isUserInRole("core-contentField-create") && !request.isUserInRole("core-contentField-update") ) {
					Layout ownerLayout = (Layout) owner;
					identifiers = WebappUtil.getIndexedFieldIdentifiers(ownerLayout.getDefinition(), request);
                    if (identifiers == null) {
                        identifiers = new TreeSet();
                    }
                    identifiers.addAll(WebappUtil.getOverridableFieldIdentifiers(ownerLayout, request));
					if ( identifiers != null && !identifiers.isEmpty() ) {
						request.setAttribute("canCreateOrUpdate", "true");
					}
				} else {
                    // (it's AP or Layout and user can create/update fields) OR
                    // (its not CP, AP or Layout)
                    if ( request.isUserInRole("core-contentField-create") || request.isUserInRole("core-contentField-update") ) {
					    request.setAttribute("canCreateOrUpdate", "true");
      				}
                }
			}
		}
	}
}
